package com.gzsxy.JUC.lock;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * 测试自旋锁
 * <p>
 * 原理就是，线程T1进去加锁，后判断!atomicReference.compareAndSet(null,thread)一直为false 就一直while循环 自旋  ，
 * 因为已经将null换位thread 返回ture 前面！就为false，直到 lock.myUnLock();解锁后，换回来，!atomicReference.compareAndSet(null,thread)这个判断为true，结束
 */
public class TestSpinlock {

    public static void main(String[] args) throws InterruptedException {
        spinlockDemo lock = new spinlockDemo();


        new Thread(() -> {

            lock.myLock();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }

        }, "T1").start();


        TimeUnit.SECONDS.sleep(1);


        new Thread(() -> {
            lock.myLock();

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        }, "T2").start();

        lock.myLock();
        lock.myUnLock();
    }
}
